package com.xjscrm.server.service.soptask.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.uzai.mobile.collect.api.dto.MicaTransDto;
import com.uzai.mobile.collect.api.dto.msg.consertoserver.MicaCustomerAddTagMsg;
import com.uzai.trace.TraceGenerate;
import com.xjscrm.common.annotation.MerId;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.common.vo.grouppull.GroupPullData;
import com.xjscrm.common.vo.grouppull.GroupPullMsgData;
import com.xjscrm.common.vo.sop.PlanData;
import com.xjscrm.common.vo.sop.TagTigger;
import com.xjscrm.server.common.util.DeviceTools;
import com.xjscrm.server.common.util.PlanDataTools;
import com.xjscrm.server.mapper.*;
import com.xjscrm.server.service.grouppull.GroupPullDataService;
import com.xjscrm.server.service.soptask.SopJobMsgService;
import com.xjscrm.server.service.soptask.SopJobTagService;
import com.xjscrm.server.vo.device.Device;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 增加标签SOP任务
 *
 * @author makejava
 * @since 2024-03-01 17:01:12
 */
@Slf4j
@Service
public class SopJobTagServiceImpl implements SopJobTagService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SopTaskDeviceMapper sopTaskDeviceMapper;
    @Autowired
    private SopTaskMapper sopTaskMapper;
    @Autowired
    private SopJobMapper sopJobMapper;
    @Autowired
    private WwCustomerTagsMapper wwCustomerTagsMapper;
    @Autowired
    private WwCustomerMapper wwCustomerMapper;
    @Autowired
    private WwDeviceMapper wwDeviceMapper;
    @Autowired
    private WwCustomerBlacklistMapper wwCustomerBlacklistMapper;
    @Autowired
    private WwGroupMapper wwGroupMapper;
    @Autowired
    private GroupPullDataService groupPullDataService;
    @Autowired
    private SopJobMsgService sopJobMsgService;
    @Autowired
    private SopTemplateMapper sopTemplateMapper;
    @Autowired
    private WwTagsMapper wwTagsMapper;


    /**
     * 添加SOP任务-手动打标签
     *
     * @param micaTransDto 手动打标签参数
     * @return 实例对象
     */
    @Async("taskExecutorForXxJob")
    @TraceGenerate //注入消息id标签
    public void addSopJobByTag(MicaTransDto micaTransDto) {
        try {

            log.info("--监控系统日志--添加SOP任务-手动打标签--");

            if (micaTransDto == null) {
                return;
            }

            if (StringUtils.isBlank(micaTransDto.getDeviceId())) {
                return;
            }

            //查询该机器人的配置方案
            log.info("--监控系统日志--查询该机器人--");
            WwDevice wwDevice = wwDeviceMapper.queryByDeviceId(micaTransDto.getDeviceId(), micaTransDto.getMerId());
            if (wwDevice == null) {
                return;
            }
            Device device = DeviceTools.transDevice(wwDevice);
            if (device == null) {
                return;
            }

            MicaCustomerAddTagMsg micaCustomerAddTagMsg = JSONObject.parseObject(JSONObject.toJSONString(micaTransDto.getData()), MicaCustomerAddTagMsg.class);
            if (micaCustomerAddTagMsg == null) {
                return;
            }

            //封装客户已打的标签
            log.info("--监控系统日志--封装客户已打的标签--");
            WwCustomer wwCustomer = wwCustomerMapper.queryByDeviceUniqueIdAndWxid(device.getDeviceUniqueId(), micaCustomerAddTagMsg.getWxid());
            if (wwCustomer == null) {
                return;
            }

            //标签id
            Long id = micaCustomerAddTagMsg.getId();
            if (id == null) {
                return;
            }
            //查询标签信息
            log.info("--监控系统日志--查询标签信息--");
            WwTags wwTags = wwTagsMapper.queryById(id);
            if (wwTags == null) {
                return;
            }


            log.info("--监控系统日志--查询客户标签--");
            List<WwCustomerTags> wwCustomerTagsList = wwCustomerTagsMapper.queryByCustomerId(wwCustomer.getId());
            if (wwCustomerTagsList == null) {
                return;
            }
            List<Long> wwCustomerTagedList = new ArrayList<>();
            wwCustomerTagedList.add(id);

            //查询该机器人配置的打标签SOP任务列表
            log.info("--监控系统日志--查询该机器人配置的打标签SOP任务列表--");
            List<SopTaskDevice> sopTaskDeviceList = sopTaskDeviceMapper.selectByDeivceUniqueIdAndType(device.getDeviceUniqueId(), 3, device.getMerId());
            if (sopTaskDeviceList != null && sopTaskDeviceList.size() >= 0) {
                for (SopTaskDevice sopTaskDevice : sopTaskDeviceList) {
                    SopTask sopTask = sopTaskMapper.selectById(sopTaskDevice.getTaskId());
                    if (sopTask != null && sopTask.getStatus().intValue() == 1) {
                        //验证是否符合手动打标签触发SOP条件
                        TagTigger tagTigger = JSONObject.parseObject(sopTask.getTrigger(), TagTigger.class);
                        boolean result = verifyCustomerTag(tagTigger, wwCustomerTagedList);
                        if (result) {
                            //查询符合条件的任意一个新客SOP方案(新会员SOP只触发一个)
                            if(sopTask.getTeaplateId() == null){
                                return;
                            }

                            SopTemplate sopTemplate = sopTemplateMapper.selectById(sopTask.getTeaplateId());
                            if(sopTemplate == null){
                                return;
                            }
                            String planDatas = sopTemplate.getPlanDatas();
                            if (StringUtils.isBlank(planDatas)) {
                                return;
                            }

                            List<PlanData> planDataList = JSONObject.parseArray(planDatas, PlanData.class);
                            if (planDataList == null || planDataList.size() == 0) {
                                return;
                            }

                            //当前时间
                            int now = DateUtil.getTime();
                            //计算发送时间
                            Integer sendTime = PlanDataTools.getSendTime(null, planDataList.get(0));
                            //保存SopJob
                            SopJob sopJob = new SopJob();
                            sopJob.setId(IdWorker.getId());
                            sopJob.setMerId(sopTask.getMerId());
                            sopJob.setTaskId(sopTask.getId());
                            sopJob.setName(sopTask.getName());
                            sopJob.setStatus(1);
                            sopJob.setType(sopTask.getType());
                            sopJob.setTeaplateId(sopTask.getTeaplateId());
                            sopJob.setTrigger(sopTask.getTrigger());
                            sopJob.setPlanDatas(sopTemplate.getPlanDatas());
                            sopJob.setWxid(wwCustomer.getWxid());
                            sopJob.setDeviceUniqueId(device.getDeviceUniqueId());
                            sopJob.setDeviceId(device.getDeviceId());
                            sopJob.setFirstTime(sendTime);
                            sopJob.setNextTime(sendTime);
                            sopJob.setPlanDatasNextIndex(0);
                            sopJob.setWxidType(0);//类型（0-客户;1-群）
                            sopJob.setCreateTime(now);
                            sopJob.setUpdateTime(now);
                            sopJobMapper.insertSelective(sopJob);

                            log.info("--监控系统日志--插入job任务--");

                        }
                    }
                }
            }

            log.info("--监控系统日志--结束添加SOP任务-手动打标签--");

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 验证符合手动打标签的SOP任务
     *
     * @param tagTigger
     * @return 符合返回true
     * @author jitwxs
     * @date 2024/4/22 12:00
     */
    private boolean verifyCustomerTag(TagTigger tagTigger, List<Long> wwCustomerTagedList) {
        try {
            if (tagTigger != null) {
                //标签列表
                List<Long> customerEnterpriseTagList = JSONObject.parseArray(tagTigger.getCustomerEnterpriseTags(), Long.class);
                if (customerEnterpriseTagList == null || customerEnterpriseTagList.size() == 0) { //没有找到，则不回复
                    return false;
                }
                //客户企业标签选项(0-含任意标签；1-含所有标签)
                Integer customerEnterpriseTagOpt = Tools.getInteger(tagTigger.getCustomerEnterpriseTagOpt());

                if (customerEnterpriseTagOpt.intValue() == 0) { //满足任意一个
                    boolean tagFlag = false;
                    for (Long customerEnterpriseTag : customerEnterpriseTagList) {
                        if (wwCustomerTagedList.contains(customerEnterpriseTag)) {//找到一个符合的，就返回通过
                            tagFlag = true;
                            break;
                        }
                    }
                    if (!tagFlag) {
                        return false;
                    }
                } else if (customerEnterpriseTagOpt.intValue() == 1) {//满足所有触发
                    if (!wwCustomerTagedList.containsAll(customerEnterpriseTagList)) {
                        return false;
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return true;
    }

    /**
     * 自动处理标签SOP阶段性任务
     *
     * @param sopJob
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    @Async("taskExecutorForXxJob")
    public void autoStepSopJobByTag(SopJob sopJob) {

        if (sopJob == null) {
            return;
        }

        //获取该任务计划数据
        String planDatas = sopJob.getPlanDatas();
        if (StringUtils.isBlank(planDatas)) {
            return;
        }

        List<PlanData> planDataList = JSONObject.parseArray(planDatas, PlanData.class);
        if (planDataList == null || planDataList.size() == 0) {
            return;
        }

        int now = DateUtil.getTime();

        //获取当前阶段性数据的下标
        Integer planDatasNextIndex = Tools.getInteger(sopJob.getPlanDatasNextIndex());
        //如果下标已经超过数据的长度，则将任务修改成已完成
        if (planDatasNextIndex >= planDataList.size()) {
            sopJob.setStatus(2); //执行完成
            sopJob.setUpdateTime(now);
            sopJobMapper.updateStatusById(sopJob);
            return;
        }

        //查询机器人
        WwDevice wwDevice = wwDeviceMapper.queryById(sopJob.getDeviceUniqueId());
        if (wwDevice == null) {
            sopJob.setStatus(0); //执行关闭
            sopJob.setUpdateTime(now);
            sopJob.setRemark("机器人未找到");
            sopJobMapper.updateStatusById(sopJob);
            return;
        }
        Device device = DeviceTools.transDevice(wwDevice);

        //查询会员
        String sendNickname = null;
        WwCustomer wwCustomer = wwCustomerMapper.queryByDeviceUniqueIdAndWxid(sopJob.getDeviceUniqueId(), sopJob.getWxid());
        if (wwCustomer == null) { //客户不存在，咋关闭
            sopJob.setStatus(0); //执行关闭
            sopJob.setUpdateTime(now);
            sopJob.setRemark("会员未找到");
            sopJobMapper.updateStatusById(sopJob);
            return;
        }

        //默认黑名单不通过
        WwCustomerBlacklist wwCustomerBlacklist = wwCustomerBlacklistMapper.selectByWxid(sopJob.getMerId(), wwCustomer.getWxid());
        if (wwCustomerBlacklist != null) { //在黑名单中
            sopJob.setStatus(0); //执行关闭
            sopJob.setUpdateTime(now);
            sopJob.setRemark("黑名单会员");
            sopJobMapper.updateStatusById(sopJob);
            return;
        }

        //替换[称呼/昵称]变量，优先称呼，在昵称
        sendNickname = wwCustomer.getNickname();
        if (StringUtils.isBlank(sendNickname)) {
            sendNickname = wwCustomer.getName();
        }

        List<WwCustomerTags> wwCustomerTagsList = wwCustomerTagsMapper.queryByCustomerId(wwCustomer.getId());
        if (wwCustomerTagsList == null) {
            return;
        }
        List<Long> wwCustomerTagedList = new ArrayList<>();
        if (wwCustomerTagsList != null && wwCustomerTagsList.size() > 0) {
            for (WwCustomerTags wwCustomerTags : wwCustomerTagsList) {
                wwCustomerTagedList.add(wwCustomerTags.getTagId());
            }
        }

        //判断该该会员是否还有此标签
        //验证是否符合手动打标签触发SOP条件
        TagTigger tagTigger = JSONObject.parseObject(sopJob.getTrigger(), TagTigger.class);
        boolean result = verifyCustomerTag(tagTigger, wwCustomerTagedList);
        if (!result){
            sopJob.setStatus(0); //执行关闭
            sopJob.setUpdateTime(now);
            sopJob.setRemark("会员标签不符合");
            sopJobMapper.updateStatusById(sopJob);
            return;
        }

        //本次的执行时间
        Integer sendTime_this = Tools.getInteger(sopJob.getNextTime());
        //获取当前需要发送的阶段性计划数据
        if(planDatasNextIndex < planDataList.size()){
            PlanData planData = planDataList.get(planDatasNextIndex);
            if (planData != null) {
                List<GroupPullData> groupPullDataList = planData.getMsgDataList();
                if (groupPullDataList != null) {
                    List<GroupPullMsgData> groupPullMsgDataList = groupPullDataService.handGroupPullData(sopJob.getMerId(), groupPullDataList, wwCustomer, device);
                    if (groupPullMsgDataList != null && groupPullMsgDataList.size() > 0) {
                        sopJobMsgService.addSopJobMsg(sopJob, sendTime_this, device, sopJob.getWxid(), sendNickname, groupPullMsgDataList);
                    }
                }
            }
        }

        //计算下一次发送时间
        //如果下标已经超过数组上线，则表示已经执行完该SOP任务
        if(planDatasNextIndex + 1 >= planDataList.size()){
            sopJob.setStatus(2);
            sopJob.setUpdateTime(now);
            sopJobMapper.updateStatusById(sopJob);
        }else{
            Integer sendTime_next = PlanDataTools.getSendTime(sopJob.getFirstTime(), planDataList.get(planDatasNextIndex + 1));
            sopJob.setNextTime(sendTime_next);
            sopJob.setPlanDatasNextIndex(planDatasNextIndex + 1);
            sopJob.setUpdateTime(now);
            sopJobMapper.updateStatusById(sopJob);
        }

    }


    /**
     * 添加SOP任务-自动同步会员标签触发标签SOP任务
     *
     * @param wwDevice 手动打标签参数
     * @return 实例对象
     */
    @Async("taskExecutorForXxJob")
    @TraceGenerate //注入消息id标签
    public void addSopJobByPushCustomerTag(@MerId Long merId, WwDevice wwDevice, WwCustomer wwCustomer) {
        try {
            log.info("--监控系统日志--添加SOP任务-自动同步会员标签--");
            if (wwDevice == null) {
                return;
            }
            Device device = DeviceTools.transDevice(wwDevice);
            if (device == null) {
                return;
            }

            //封装客户已打的标签
            if (wwCustomer == null) {
                return;
            }

            log.info("--监控系统日志--查询客户标签--");
            List<WwCustomerTags> wwCustomerTagsList = wwCustomerTagsMapper.queryByCustomerId(wwCustomer.getId());
            if (wwCustomerTagsList == null) {
                return;
            }
            List<Long> wwCustomerTagedList = new ArrayList<>();
            if (wwCustomerTagsList != null && wwCustomerTagsList.size() > 0) {
                for (WwCustomerTags wwCustomerTags : wwCustomerTagsList) {
                    wwCustomerTagedList.add(wwCustomerTags.getTagId());
                }
            }

            //查询该机器人配置的打标签SOP任务列表
            log.info("--监控系统日志--查询该机器人配置的打标签SOP任务列表--");
            List<SopTaskDevice> sopTaskDeviceList = sopTaskDeviceMapper.selectByDeivceUniqueIdAndType(device.getDeviceUniqueId(), 3, device.getMerId());
            if (sopTaskDeviceList != null && sopTaskDeviceList.size() >= 0) {
                for (SopTaskDevice sopTaskDevice : sopTaskDeviceList) {
                    SopTask sopTask = sopTaskMapper.selectById(sopTaskDevice.getTaskId());
                    if (sopTask != null && sopTask.getStatus().intValue() == 1) {
                        //验证是否符合手动打标签触发SOP条件
                        TagTigger tagTigger = JSONObject.parseObject(sopTask.getTrigger(), TagTigger.class);
                        boolean result = verifyCustomerTag(tagTigger, wwCustomerTagedList);
                        if (result) {

                            //查询此群是否已经有进行中的SOP任务
                            SopJob sopJob_old = sopJobMapper.selectUniqueByTagSop(wwCustomer.getWxid(), wwDevice.getId(), sopTask.getId(), sopTask.getMerId());
                            if (sopJob_old != null) { //此会员已经触发了该标签任务的JOB
                                return;
                            }

                            //查询符合条件的任意一个新客SOP方案(新会员SOP只触发一个)
                            if(sopTask.getTeaplateId() == null){
                                return;
                            }

                            SopTemplate sopTemplate = sopTemplateMapper.selectById(sopTask.getTeaplateId());
                            if(sopTemplate == null){
                                return;
                            }
                            String planDatas = sopTemplate.getPlanDatas();
                            if (StringUtils.isBlank(planDatas)) {
                                return;
                            }

                            List<PlanData> planDataList = JSONObject.parseArray(planDatas, PlanData.class);
                            if (planDataList == null || planDataList.size() == 0) {
                                return;
                            }

                            //当前时间
                            int now = DateUtil.getTime();
                            //计算发送时间
                            Integer sendTime = PlanDataTools.getSendTime(null, planDataList.get(0));
                            //保存SopJob
                            SopJob sopJob = new SopJob();
                            sopJob.setId(IdWorker.getId());
                            sopJob.setMerId(sopTask.getMerId());
                            sopJob.setTaskId(sopTask.getId());
                            sopJob.setName(sopTask.getName());
                            sopJob.setStatus(1);
                            sopJob.setType(sopTask.getType());
                            sopJob.setTeaplateId(sopTask.getTeaplateId());
                            sopJob.setTrigger(sopTask.getTrigger());
                            sopJob.setPlanDatas(sopTemplate.getPlanDatas());
                            sopJob.setWxid(wwCustomer.getWxid());
                            sopJob.setDeviceUniqueId(device.getDeviceUniqueId());
                            sopJob.setDeviceId(device.getDeviceId());
                            sopJob.setFirstTime(sendTime);
                            sopJob.setNextTime(sendTime);
                            sopJob.setPlanDatasNextIndex(0);
                            sopJob.setWxidType(0);//类型（0-客户;1-群）
                            sopJob.setCreateTime(now);
                            sopJob.setUpdateTime(now);
                            sopJobMapper.insertSelective(sopJob);

                            log.info("--监控系统日志--插入job任务--");

                        }
                    }
                }
            }

            log.info("--监控系统日志--结束添加SOP任务-自动同步会员标签--");

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}
